<?php
class AssignmentsController extends AppController {

	var $name = 'Assignments';
	var $helpers = array('Html', 'Form' );
	var $uses = array('Assignment', 'User', 'Semester', 'Apartment');

	function admin_index() {
		$this->redirect('/admin/semesters');
	}

	function admin_list($apartmentId = null) {
		$this->Assignment->recursive = 3;
		$this->set('assignments', $this->Assignment->findAllByApartmentId($apartmentId));
		$this->Apartment->recursive = 2;
		$this->set('apartment', $this->Apartment->findByApartmentId($apartmentId));
	}

	function admin_chooseSemester() {
		if (empty($this->data)) {
			$this->set('semesterList', $this->Semester->getSemesterList());
			return;
		}

		$semesterId = $this->data['Assignment']['semester_id'];
		$this->redirect("admin/assignments/add/$semesterId");
	}

	function admin_add($apartmentId = null) {
		if ($apartmentId == null) {
			$this->redirect('/admin/semesters');
			return;
		}
		$this->set('apartmentId', $apartmentId);
		$this->set('userList', $this->User->getUserList());
		$this->set('apartmentList', $this->Apartment->getNumberAndSemesterList());
		if (empty($this->data)) {
			$this->render();
		} else {
			$this->cleanUpFields();
			$this->data['Assignment']['apartment_id'] = $apartmentId;
			if ($this->Assignment->save($this->data)) {
				$this->Session->setFlash('The Assignment has been saved');
				$this->redirect('/admin/assignments/list/'.$apartmentId);
			} else {
				$this->Session->setFlash('Please correct errors below.');
			}
		}
	}

	function admin_edit($assignmentId = null) {
		if (!$assignmentId) {
			$this->Session->setFlash('Invalid id for Assignment');
			$this->redirect('/admin/semesters');
			return;
		}

		if (empty($this->data)) {
			$this->data = $this->Assignment->read(null, $assignmentId);
			$this->set('userList', $this->User->getUserList());
		} else {
			$this->cleanUpFields();
			if ($this->Assignment->save($this->data)) {
				$this->Session->setFlash('The Assignment has been saved');
				$apartmentId = $this->data['Assignment']['apartment_id'];
				$this->redirect('/admin/assignments/list/'.$apartmentId);
			} else {
				$this->Session->setFlash('Please correct errors below.');
				$semesterId = $this->data['Assignment']['semester_id'];
				$this->set('userList', $this->User->getUserList());
				$this->set('semesterApartmentList', $this->SemesterApartment->getSemesterApartmentList($semesterId));
			}
		}
	}

	function admin_delete($id = null) {
		if ($id == null) {
			$this->Session->setFlash('Invalid id');
			$this->redirect('/admin/semesters');
			return;
		}

		$assignment = $this->Assignment->read(null, $id);
		if ($this->Assignment->del($id)) {
			$this->Session->setFlash('The assignment deleted: id '.$id.'');
			$this->redirect('/admin/assignments/list/'.$assignment['Assignment']['apartment_id']);
		}
	}
}
?>
